package helen.core.tools.update;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import helen.core.R;
import helen.core.net.HttpServiceClient;

public class UpdateManager {
    // 文件分隔符
    private static final String FILE_SEPARATOR = "/";
    // 外存sdcard存放路径
    private static final String FILE_PATH = Environment.getExternalStorageDirectory() + FILE_SEPARATOR + "autoupdate" + FILE_SEPARATOR;
    // 下载应用存放全路径
    private static final String FILE_NAME = FILE_PATH + "autoupdate.apk";
    // 更新应用版本标记
    private static final int UPDARE_TOKEN = 0x29;
    // 准备安装新版本应用标记
    private static final int INSTALL_TOKEN = 0x31;
    // 检查到有更新的标识
    private static final int IS_NEED_UPDATE = 0x35;

    private Context context;
    private String message = "检测到本程序有新版本发布，建议您更新！";
    // 以华为天天聊hotalk.apk为例
    private String spec = "";
    // 下载应用的对话框
    private Dialog dialog;
    // 下载应用的进度条
    private ProgressBar progressBar;
    // 进度条的当前刻度值
    private int curProgress;
    // 用户是否取消下载
    private boolean isCancel;
    private String CHECK_URL = "http://192.168.1.95:8080/schedule/ApkUpdateService?id=1";
    private UpdateModel model;
    private String appVersion = "";
    private int versionCode = 0;

    public UpdateManager(Context context) {
        this.context = context;
    }


    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDARE_TOKEN:
                    progressBar.setProgress(curProgress);
                    break;

                case INSTALL_TOKEN:
                    installApp();
                    break;

                case IS_NEED_UPDATE:
                    if(!model.versionCode.equals(versionCode+"")) {
                        showNoticeDialog();
                    }
                    break;
            }
        }
    };





    /**
     * 检测应用更新信息
     */
    public void checkUpdateInfo() {
        PackageManager manager = context.getPackageManager();
        try { PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            appVersion = info.versionName; //版本名
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try { PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            versionCode = info.versionCode; //版本号

        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpServiceClient client = new HttpServiceClient();
                HashMap<String, String> map = new HashMap<>();
                String result = client.doPost(CHECK_URL, map);

                try {
                    JSONArray array = new JSONArray(result);

                    if (array.length() != 0) {
                        model = new UpdateModel();
                        JSONObject object = array.getJSONObject(0);
                        model.FileName = object.getString("FileName");
                        model.description = object.getString("description");
                        model.fileSize = object.getString("fileSize");
                        model.fileUrl = object.getString("fileUrl");
                        model.versionCode = object.getString("versionCode");
                        model.version = object.getString("version");
                        model.versionDescription = object.getString("versionDescription");
                        model.publishDate = object.getString("publishDate");
                        model.appName = object.getString("appName");
                        handler.sendEmptyMessage(IS_NEED_UPDATE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 显示提示更新对话框
     */
    private void showNoticeDialog() {
        message = "应用名称：" + model.appName + "\n";
        message += "最新版本：" + model.versionDescription + "\n";
        message += "当前版本版本：" + appVersion + "\n";
        message += "更新大小：" + model.fileSize + "\n";
        message += "发布时间：" + model.publishDate + "\n";
        message += "更新日志：" + model.description + "\n";

        new AlertDialog.Builder(context)
                .setTitle("软件版本更新")
                .setMessage(message)
                .setPositiveButton("下载", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        showDownloadDialog();
                    }
                }).setNegativeButton("以后再说", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).create().show();
    }

    /**
     * 显示下载进度对话框
     */
    private void showDownloadDialog() {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_progressbar, null);
        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("软件版本更新");
        builder.setView(view);
        builder.setNegativeButton("取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                isCancel = true;
            }
        });
        dialog = builder.create();
        dialog.show();
        downloadApp();
    }

    /**
     * 下载新版本应用
     */
    private void downloadApp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url = null;
                InputStream in = null;
                FileOutputStream out = null;
                HttpURLConnection conn = null;
                try {
                    url = new URL(model.fileUrl);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    long fileLength = conn.getContentLength();
                    in = conn.getInputStream();
                    File filePath = new File(FILE_PATH);
                    if (!filePath.exists()) {
                        filePath.mkdir();
                    }
                    out = new FileOutputStream(new File(FILE_NAME));
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    long readedLength = 0l;
                    while ((len = in.read(buffer)) != -1) {
                        // 用户点击“取消”按钮，下载中断
                        if (isCancel) {
                            break;
                        }
                        out.write(buffer, 0, len);
                        readedLength += len;
                        curProgress = (int) (((float) readedLength / fileLength) * 100);
                        handler.sendEmptyMessage(UPDARE_TOKEN);
                        if (readedLength >= fileLength) {
                            dialog.dismiss();
                            // 下载完毕，通知安装
                            handler.sendEmptyMessage(INSTALL_TOKEN);
                            break;
                        }
                    }
                    out.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        }).start();
    }

    /**
     * 安装新版本应用
     */
    private void installApp() {
        File appFile = new File(FILE_NAME);
        if (!appFile.exists()) {
            return;
        }
        // 跳转到新版本应用安装页面
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://" + appFile.toString()), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }
}
